using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Helpers
{
    public static class StringHelper
    {
        public static string FormatIfExists(string format, params object[] args)
        {
            if (Array.TrueForAll<object>(args, ObjectNotNull))
            {
                return SafeFormat(format, args);
            }
            else
            {
                return null;
            }
        }

        public static string SafeFormat(object input)
        {
            return SafeFormat("{0}", input);
        }

        public static string SafeFormat(string format, params object[] args)
        {
            if (String.IsNullOrEmpty(format))
            {
                return "";
            }
            else
            {
                if (format.Length > 0 && args.Length == 0)
                {
                    return HttpContext.Current.Server.HtmlEncode(format);
                }
                else
                {
                    string[] safeArgs = Array.ConvertAll<object, string>(args, HtmlEncode);
                    return string.Format(format, safeArgs);
                }
            }
        }

        private static bool ObjectNotNull(object obj)
        {
            if (obj is string)
            {
                return !string.IsNullOrEmpty(obj as string);
            }
            else
            {
                return (obj != null);
            }
        }

        private static string HtmlEncode(object obj)
        {
            if (obj != null)
            {
                return HttpContext.Current.Server.HtmlEncode(obj.ToString());
            }
            else
            {
                return "";
            }
        }

        public static string GetRelativePath(string relativeUrl)
        {
            if (relativeUrl.StartsWith("/") || relativeUrl.StartsWith(@"\"))
            {
                relativeUrl = relativeUrl.Substring(1);
            }

            return string.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings["RootPath"], relativeUrl);
        }

        static System.Text.RegularExpressions.Regex regexHTML =
            new System.Text.RegularExpressions.Regex(@"<.*?>");
        public static string GetFirstChars(string content, int numberOfChars)
        {
            content = regexHTML.Replace(content, "");
            if (content.Length > numberOfChars)
            {
                return Helpers.StringHelper.SafeFormat(content.Substring(0, numberOfChars));
            }
            else
            {
                return Helpers.StringHelper.SafeFormat(content);
            }
        }
    }
}